package cn.innosmart.aq.view.fragment;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.innosmart.aq.R;
import cn.innosmart.aq.util.EditTextCheckUtil;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.view.activity.CountActivity;

/**
 * Created by David on 2015/7/15.
 */
public class CountVerifyFragment extends BaseFragment implements INetworkInteractUtil {
    private final int REGISTVERIFYSUCCESS = 0;
    private final int FINDPASSWORDVERIFYSUCCESS = 0;
    private final int USERNAMEALREADYUSES = -1;
    private final int REGISTVERIFYWAIT = -2;
    private final int REGISTVERIFYFAILD = -3;
    private final int USERHASNOTREGISTER = -4;
    private final int ERROR = 2;
    private final int REGIST = 1;
    private final int FINDPASSWORD = 2;
    private int flag = 0;
    private CountActivity mActivity;
    private View view;
    private NetworkInteractUtil networkInteractUtil;
    private EditText etNum;
    private Button btNext;
    private Spinner spinnerPhonePrefix;
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    };
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.bt_next:
                    int p = spinnerPhonePrefix.getSelectedItemPosition();
                    String prefix = "+086";
                    if (p == 0) {
                        prefix = "+086";
                    } else if (p == 1) {
                        prefix = "+886";
                    }
                    String num = etNum.getText().toString().trim();
                    if (EditTextCheckUtil.checkTelNo(prefix, num)) {
                        if (flag == REGIST) {
                            networkInteractUtil.registVerify(prefix+num);
                        } else if (flag == FINDPASSWORD) {
                            networkInteractUtil.findPasswordVerify(num);
                        }
                    } else {
                        System.out.println("reg phone no error");
                    }
//                    mHandler.sendEmptyMessage(REGISTVERIFYSUCCESS);
                    break;
            }
        }
    };
    private int verification_code;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ERROR:
                    String error = (String) msg.obj;
                    showToast(error);
                    break;
                case REGISTVERIFYSUCCESS:
                    showToast(getActivity().getString(R.string.verifycode_send_success));
                    switchToRegisterFragment();
                    detectSMSServiceNo();
                    break;
                case USERNAMEALREADYUSES:
                    String message = (String) msg.obj;
                    showToast(message);
                    break;
                case REGISTVERIFYWAIT:
                    switchToRegisterFragment();
                    break;
                case USERHASNOTREGISTER:
                    break;
                case REGISTVERIFYFAILD:
                    String failed = (String) msg.obj;
                    showToast(failed);
                    break;
                case REGIST:
                    getActivity().onBackPressed();
                    break;
            }
        }
    };

    private Uri SMS_INBOX = Uri.parse("content://sms/");

    public void getSmsFromPhone() {
        ContentResolver cr = getActivity().getContentResolver();
        String[] projection = new String[]{"body"};//"_id", "address", "person",, "date", "type
        String where = "date >  "
                + (System.currentTimeMillis() - 100 * 60 * 1000);
        Cursor cur = cr.query(SMS_INBOX, projection, where, null, "date desc");
        if (null == cur)
            return;
        if (cur.moveToNext()) {
            String number = cur.getString(cur.getColumnIndex("address"));//手机号
            String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
            String body = cur.getString(cur.getColumnIndex("body"));
            System.out.println("sms body: " + body);
            //这里我是要获取自己短信服务号码中的验证码~~
//            Pattern pattern = Pattern.compile(" [a-zA-Z0-9]{10}");
//            Matcher matcher = pattern.matcher(body);
//            if (matcher.find()) {
//                String res = matcher.group().substring(1, 11);
//            }
        }
    }

    private void detectSMSServiceNo() {
        getSmsFromPhone();
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    private void assignViews(View view) {
        spinnerPhonePrefix = (Spinner) view.findViewById(R.id.spinner_phone_prefix_reg);
        etNum = (EditText) view.findViewById(R.id.et_num);
        btNext = (Button) view.findViewById(R.id.bt_next);
        btNext.setOnClickListener(mBtnOnClickListener);
//        tvLocal = (TextView) view.findViewById(R.id.tv_local);
//        if (SystemConstant.LOCAL_MODE == SystemConstant.MODE_CH) {
//            tvLocal.setText("+86");
//        } else if (SystemConstant.LOCAL_MODE == SystemConstant.MODE_TW) {
//            tvLocal.setText("+886");
//        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_countregister_verify, container, false);
        networkInteractUtil = new NetworkInteractUtil(this);
        mActivity = (CountActivity) getActivity();
        assignViews(view);
        setBar();
        return view;
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
//        toolbar.setNavigationIcon(R.drawable.toolbar_back);
//        toolbar.setTitle(mActivity.getString(R.string.verify_telno));
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        ((ImageView) getActivity().findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        toolbar.setTitle("");
        ((TextView) getActivity().findViewById(R.id.tv_toolbar)).setText(getString(R.string.verify_telno));
//        setSupportActionBar(toolbar);
        getActivity().findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mDrawer.openDrawer(GravityCompat.START);
                getActivity().onBackPressed();
            }
        });
    }

    public void swichCountLoginFragment() {
        CountLoginFragment fragment;
        FragmentManager fm = getFragmentManager();
        fragment = (CountLoginFragment) fm.findFragmentByTag("countlogin");
        if (fragment == null) {
            System.out.println("create");
            fragment = new CountLoginFragment();
        }
        FragmentTransaction tx = fm.beginTransaction();
        tx.add(R.id.ll_content, fragment, "countlogin");
        tx.commit();
    }

    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override

    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (flag.equals(networkInteractUtil.REGISTVERIFY)) {
            switch (ret) {
                case 0:
                    try {
                        JSONObject jsonResult = new JSONObject((String) object);
                        verification_code = jsonResult.getInt("verification_code");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(REGISTVERIFYSUCCESS);
                    break;
                case 1:
                    Message usernameAlreadyUsed = mHandler.obtainMessage();
                    usernameAlreadyUsed.obj = object;
                    usernameAlreadyUsed.what = USERNAMEALREADYUSES;
                    mHandler.sendMessage(usernameAlreadyUsed);
                    break;
                case 2:
                    mHandler.sendEmptyMessage(REGISTVERIFYWAIT);
                    break;
                default:
                    Message msg = mHandler.obtainMessage();
                    msg.what = REGISTVERIFYFAILD;
                    msg.obj = object;
                    mHandler.sendMessage(msg);
                    break;
            }
        } else if (flag.equals(networkInteractUtil.FINDPASSWORDVERIFY)) {
            switch (ret) {
                case 0:
                    try {
                        JSONObject jsonResult = new JSONObject((String) object);
                        verification_code = jsonResult.getInt("verification_code");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(FINDPASSWORDVERIFYSUCCESS);
                    break;
                case 1:
                    Message msg = mHandler.obtainMessage();
                    msg.what = REGISTVERIFYFAILD;
                    msg.obj = object;
                    mHandler.sendMessage(msg);
                    break;
                case 2:
                    mHandler.sendEmptyMessage(REGISTVERIFYWAIT);
                    break;
                default:
                    Message obtainMessage = mHandler.obtainMessage();
                    obtainMessage.what = REGISTVERIFYFAILD;
                    obtainMessage.obj = object;
                    mHandler.sendMessage(obtainMessage);
                    break;
            }
        }
    }

    /**
     * 切换到注册页面
     */
    private void switchToRegisterFragment() {
        FragmentManager fm = getFragmentManager();
        if (flag == REGIST) {
            CountRegisterFragment fragment;
            fragment = (CountRegisterFragment) fm.findFragmentByTag("register");
            if (fragment == null) {
                fragment = new CountRegisterFragment();
                fragment.setUserName(etNum.getText().toString().trim());
                fragment.setVerification_code(verification_code);
                fragment.setCountdown(60);
            } else {
                fragment.setUserName(etNum.getText().toString().trim());
                fragment.setVerification_code(verification_code);
            }
            FragmentTransaction tx = fm.beginTransaction();
            tx.replace(R.id.ll_content, fragment, "register");
            tx.addToBackStack(null);
            tx.commit();
        } else if (flag == FINDPASSWORD) {
            CountFindPasswordFragment fragment;
            fragment = (CountFindPasswordFragment) fm.findFragmentByTag("findpd");
            if (fragment == null) {
                fragment = new CountFindPasswordFragment();
                fragment.setUserName(etNum.getText().toString().trim());
                fragment.setVerification_code(verification_code);
                fragment.setCountdown(60);
            } else {
                fragment.setUserName(etNum.getText().toString().trim());
                fragment.setVerification_code(verification_code);
            }
            FragmentTransaction tx = fm.beginTransaction();
            tx.replace(R.id.ll_content, fragment, "findpd");
            tx.addToBackStack(null);
            tx.commit();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }
}
